% Create Global variables to use in estimation

disp('Creating data arrays for run.');
cp=XMAT(:,1); % person
 
nn=zeros(NCS,1);
for n=1:NCS;
    nn(n,1)=sum(XMAT(:,2) == n,1);
end;
NALTMAX=max(nn);  %Maximum number of alternatives in any choice situation

nn=zeros(NP,1);
for n=1:NP;
   k=(XMAT(:,1)==n);
   k=XMAT(k,2);
   nn(n,1)=1+k(end,1)-k(1,1);
end;
NCSMAX=max(nn);  %Maximum number of choice situations faced by any person

NTAKES=NDRAWS./NMEM; %This tells code how many passes through the draws are needed 
                           % given NMEM people in each pass.
if WANTWGT == 1;
    WGT=zeros(1,NP);
    for r=1:NP
        WGT(1,r)=mean(XMAT(cp == r,IDWGT),1);
    end
    WGT=WGT.*(NP./sum(WGT,2));
else
    WGT=[];
end

% Data arrays 
% All variables are differenced from the chosen alternative
% Only nonchosen alternatives are included, since V for chosen alt =0
% This reduces number of calculations for logit prob and eliminates need to
% retain dependent variable.

X=zeros(NALTMAX-1,NCSMAX,NV,NP); % Explanatory variables with random coefficients 
%                                  for all choice situations, for each person 
XF=zeros(NALTMAX-1,NCSMAX,NF,NP); % Explanatory variables with fixed coefficients 
%                                  for all choice situations, for each person 
S=zeros(NALTMAX-1,NCSMAX,NP); % Identification of the alternatives in each choice situation, for each person

for n=1:NP;  %loop over people
 cs=XMAT(cp == n,2);
 yy=XMAT(cp == n,3);
 if NV > 0
    xx=XMAT(cp == n, IDV(:,1));
 end
 if NF > 0
    xxf=XMAT(cp == n, IDF(:,1));
 end
 t1=cs(1,1);
 t2=cs(end,1);
 for t=t1:t2; %loop over choice situations
     k=sum(cs==t)-1; %One less than number of alts = number of nonchosen alts
     S(1:k,1+t-t1,n)=ones(k,1);
     if NV>0
        X(1:k,1+t-t1,:,n)=xx(cs==t & yy == 0,:)-repmat(xx(cs==t & yy == 1,:),k,1);
     end
     if NF>0
        XF(1:k,1+t-t1,:,n)=xxf(cs==t & yy == 0,:)-repmat(xxf(cs==t & yy == 1,:),k,1);
     end;
 end
end

% Do not clear out XMAT, such that BOOT can access the
%original data!

%clear global XMAT 
clear cp cs yy xx t1 t2 k nn